package scatter.test.rest.test.temp.yd;

import cn.hutool.core.util.StrUtil;
import com.google.common.base.Preconditions;
import org.apache.commons.codec.digest.DigestUtils;

import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 签名
 *
 * @author yehui
 * @date 2020/8/21
 */
public final class SignUtil {

    /**
     * 参数签名
     *
     * @param target 签名的对象
     * @param secret 秘钥
     * @return
     */
    public static String sign(Map<String, String> target, String secret) {
        Preconditions.checkArgument(Objects.nonNull(target) && !target.isEmpty(), "签名的对象不能为空");
        Preconditions.checkArgument(StrUtil.isNotBlank(secret), "秘钥不能为空");

        final String signString = target.entrySet()
            .stream()
            .filter(entry -> StrUtil.isNotBlank(entry.getKey()) && StrUtil.isNotBlank(entry.getValue()))
            .filter(entry -> !StrUtil.equals("sign", entry.getKey()))
            .sorted(Map.Entry.comparingByKey())
            .map(entry -> entry.getKey() + entry.getValue())
            .collect(Collectors.joining());
        Preconditions.checkArgument(StrUtil.isNotEmpty(signString), "参与签名的参数为空");

        return DigestUtils.md5Hex(signString + secret).toLowerCase();
    }

}
